import 'nprogress/nprogress.css'

import nprogress from 'nprogress'

import router from '@/router'

import setting from './setting'
import request from './utils/request'

// 配置 nprogress
nprogress.configure({ showSpinner: false })

// 缓存 store 实例,避免重复导入
let userStoreInstance: any = null

// 获取用户 store 实例的工具函数
const getUserStore = async () => {
  if (!userStoreInstance) {
    const { default: useUserStore } = await import('./store/modules/user')
    userStoreInstance = useUserStore()
  }
  return userStoreInstance
}

// 路由白名单
const WHITE_LIST = ['/login']

// 全局前置守卫
router.beforeEach(async (to, from, next) => {
  // 设置页面标题
  document.title = `${to.meta.title} | ${setting.title}`
  nprogress.start()

  try {
    const userStore = await getUserStore()
    const { token, username } = userStore

    // 已登录用户访问登录页,重定向到首页
    if (token && to.path === '/login') {
      next({ path: '/' })
      return
    }

    // 未登录用户访问非白名单页面,重定向到登录页
    if (!token && !WHITE_LIST.includes(to.path)) {
      next({ 
        path: '/login', 
        query: { redirect: to.path } 
      })
      return
    }

    // 已登录但用户信息不完整,执行登出操作
    if (token && !username) {
      await userStore.userLogout()
      next({ 
        path: '/login', 
        query: { redirect: to.path } 
      })
      return
    }

    // 正常放行
    next()
  } catch (error) {
    console.error('路由守卫错误:', error)
    // 发生错误时,清除用户信息并跳转登录页
    const userStore = await getUserStore()
    await userStore.userLogout()
    next({ path: '/login' })
  }
})

// 全局后置守卫
router.afterEach(async (route) => {
  try {
    const userStore = await getUserStore()
    const { userid } = userStore

    // 发送路由切换消息到后端
    if (userid && route.meta?.title) {
      request.post('/chat/updatechatidmessge', {
        userId: userid,
        routerPage: route.meta.title,
      }).then((res) => {
        console.log('路由切换成功:', res)
      }).catch((error) => {
        console.error('发送路由切换消息失败:', error)
      })
    }
  } catch (error) {
    console.error('后置守卫错误:', error)
  } finally {
    nprogress.done()
  }
})